import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.sound.sampled.*;

class Figure8 {
    private AlphaGUI GUI;
    private Rec recorder;

    public static void main(String[] args) {
        final Figure8 figure8 = new Figure8();

        figure8.GUI = new AlphaGUI(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                figure8.spawn();
            }
        }, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                figure8.recorder.confirm();
            }
        },  new ActionListener() {
            @Override public void actionPerformed(ActionEvent event) {
                    figure8.recorder.metronomeOnOff();
                }
        },  new ActionListener() {
            @Override public void actionPerformed(ActionEvent event) {
                figure8.recorder.pause();
            }
        });

        figure8.GUI.setVisible(true);
    }

    public void spawn() {
        final Figure8 hack = this;
        
        new Thread(new Runnable() {
            @Override
            public void run() {
                hack.run("alpha_demo.wav", hack.GUI.getTempo(),
                        hack.GUI.getBeats(), hack.GUI.getBars());
            }
        }).start();
    }

    //takes the filename, tempo, beats and bars as input to receive samples from
    //an input line from a microphone input or a line-level analog input at CD 
    //quality signed 16 bit, stereo samples 44.1kHz in pulse code modulation 
    //encoding) to the "filename" currently alpha_demo.wav.
    //How long each recorded loop is is also calculated here from the tempo,
    //beats and bars input variables.
    public void run(String filename, int tempo, int beats, int bars) {
        int type = 4;
        double time = (60.0 / tempo) * beats * (4.0 / type) * bars;
        AudioFileFormat.Type targetType = AudioFileFormat.Type.WAVE;
        //create a Rec object
        recorder = new Rec(targetType, filename, beats, bars, time);
        //start recording
        recorder.record();
    }

    //my printing function
    static void print(String line) {
        System.out.println(line);
    }        
}
